package com.kun.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.kun.entity.Comment;
import com.kun.entity.CommentExample;
import com.kun.entity.CommentExample.Criteria;
import com.kun.entity.UserLikeCommentExample;
import com.kun.entity.Wishing;
import com.kun.mapper.cluster.custom.CommentMapperRCustom;
import com.kun.mapper.master.MasterUserLikeCommentMapper;
import com.kun.mapper.master.custom.CommentMapperWCustom;
import com.kun.mapper.master.custom.WishMapperWCustom;
import com.kun.service.CommentService;
import com.kun.util.PaginationUtil;

/**
 * @description: 评论业务类
 * @author: KM
 * 2018年4月10日
 */
@Service
public class CommentServiceImpl implements CommentService {
	
	@Autowired
	private CommentMapperRCustom clusterCommentMapper;
	
	@Autowired
	private CommentMapperWCustom commentMapperWCustom;
	
	@Autowired
	private WishMapperWCustom wishMapperWCustom;
	
	@Autowired 
	private MasterUserLikeCommentMapper masterUserLikeCommentMapper;
	
	@Autowired
	private HashOperations<String, String, Object> hashOperations;
	
	@Autowired
	private RedisTemplate<String, Object> redisTemplate;
	
	@Autowired
	private SetOperations<String, Object> setOperations;
	
	/**
	 * 分页条件查询许愿
	 * */
	public Map<String,Object> selectAllWish(int begin,int length,String jsonString,String userId){
		CommentExample example = new CommentExample();
		example.setOrderByClause("likes desc,add_time desc");
		Criteria ca = example.createCriteria();
		ca.andWishIdIsNotNull();
		ca.andActivityIdIsNull();
		ca.andBookIdIsNull();
		ca.andFatherCommentidIsNull();//首次发起的评论  不存在父id
		if(jsonString!=null&&"1".equals(jsonString)){
			ca.andStarEqualTo("1");
		}else{
			ca.andStarIsNull();
		}
		int allRecord = clusterCommentMapper.countByExample(example);
		PaginationUtil pagination = new PaginationUtil((begin-1)*length,length,allRecord);
		example.setPagination(pagination);
		List<Comment> lc = new ArrayList<Comment>();
		List<Comment> resultList = new ArrayList<Comment>();
		if(userId!=null){
			lc = clusterCommentMapper.selectWishByExampleOnUser(example, userId);
			for(int i=0;i<lc.size();i++){
				Comment c = lc.get(i);
				int cId = c.getId();
				@SuppressWarnings("unchecked")
				Map<String,Object> map = (Map<String,Object>)hashOperations.get("USER_LIKE_COMMENT_"+cId, userId);
				if(map!=null){
					if(!map.isEmpty()){
						String state = (String)map.get("state");
						if("1".equals(state)){
							c.setIsCurrentUserLike("1");
						}else if("0".equals(state)){
							c.setIsCurrentUserLike(null);
						}
					}
				}
				String n = (String)redisTemplate.opsForValue().get("post_counter_"+cId);
				if(n!=null){
					Integer number = Integer.parseInt(n);
					if(number!=null){
						c.setLikes(c.getLikes()+number);//数据库点赞数+redis点赞数
					}
				}
				resultList.add(c);
			}
		}else{
			lc = clusterCommentMapper.selectWishByExample(example);
			for(int i=0;i<lc.size();i++){
				Comment c = lc.get(i);
				int cId = c.getId();
				String n = (String)redisTemplate.opsForValue().get("post_counter_"+cId);
				if(n!=null){
					Integer number = Integer.parseInt(n);
					if(number!=null){
						c.setLikes(c.getLikes()+number);//数据库点赞数+redis点赞数
					}
				}
				resultList.add(c);
			}
		}
		Map<String,Object> resultMap = new HashMap<String,Object>();
		resultMap.put("allRecord", allRecord);
		resultMap.put("wishList", resultList);
		return resultMap;
	}
	
	
	
	/**
	 * 查询图书评论数
	 * */
	public int selectCountBookComment(int bookId){
		CommentExample example = new CommentExample();
		Criteria ca = example.createCriteria();
		ca.andBookIdEqualTo(bookId);
		return clusterCommentMapper.countByExample(example);
	}

	/**
	 * 查询 某图书的所有发起评论
	 * */
	public List<Comment> selectExampleComment(Comment comment,String userId){
		CommentExample example = new CommentExample();
		example.setOrderByClause("likes desc,add_time desc");
		Criteria ca = example.createCriteria();
		if(comment.getBookId()!=null){
			ca.andBookIdEqualTo(comment.getBookId());
		}
		ca.andFatherCommentidIsNull();//首次发起的评论  不存在父id
		List<Comment> lc = new ArrayList<Comment>();
		List<Comment> resultList = new ArrayList<Comment>();
		if(userId!=null){
			lc = clusterCommentMapper.selectByExampleOnUser(example, userId);
			for(int i=0;i<lc.size();i++){
				Comment c = lc.get(i);
				int cId = c.getId();
				@SuppressWarnings("unchecked")
				Map<String,Object> map = (Map<String,Object>)hashOperations.get("USER_LIKE_COMMENT_"+cId, userId);
				if(map!=null){
					if(!map.isEmpty()){
						String state = (String)map.get("state");
						if("1".equals(state)){
							c.setIsCurrentUserLike("1");
						}else if("0".equals(state)){
							c.setIsCurrentUserLike(null);
						}
					}
				}
				String n = (String)redisTemplate.opsForValue().get("post_counter_"+cId);
				if(n!=null){
					Integer number = Integer.parseInt(n);
					if(number!=null){
						c.setLikes(c.getLikes()+number);//数据库点赞数+redis点赞数
					}
				}
				resultList.add(c);
			}
		}else{
			lc = clusterCommentMapper.selectByExample(example);
			for(int i=0;i<lc.size();i++){
				Comment c = lc.get(i);
				int cId = c.getId();
				String n = (String)redisTemplate.opsForValue().get("post_counter_"+cId);
				if(n!=null){
					Integer number = Integer.parseInt(n);
					if(number!=null){
						c.setLikes(c.getLikes()+number);//数据库点赞数+redis点赞数
					}
				}
				resultList.add(c);
			}
		}
		if(resultList.size()>0){
			return resultList;
		}else{
			return null;
		}
	}
	
	/**
	 * 查询 子评论
	 * */
	public List<Comment> selectSonComment(int cid,String userId){
		List<Comment> lc = new ArrayList<Comment>();
		List<Comment> resultList = new ArrayList<Comment>();
		if(userId!=null){
			lc = clusterCommentMapper.selectSonCommentByCidOnUser(cid, userId);
			for(int i=0;i<lc.size();i++){
				Comment c = lc.get(i);
				int cId = c.getId();
				@SuppressWarnings("unchecked")
				Map<String,Object> map = (Map<String,Object>)hashOperations.get("USER_LIKE_COMMENT_"+cId, userId);
				if(map!=null){
					if(!map.isEmpty()){
						String state = (String)map.get("state");
						if("1".equals(state)){
							c.setIsCurrentUserLike("1");
						}else if("0".equals(state)){
							c.setIsCurrentUserLike(null);
						}
					}
				}
				String n = (String)redisTemplate.opsForValue().get("post_counter_"+cId);
				if(n!=null){
					Integer number = Integer.parseInt(n);
					if(number!=null){
						c.setLikes(c.getLikes()+number);//数据库点赞数+redis点赞数
					}
				}
				resultList.add(c);
			}
		}else{
			lc = clusterCommentMapper.selectSonCommentByCid(cid);
			for(int i=0;i<lc.size();i++){
				Comment c = lc.get(i);
				int cId = c.getId();
				String n = (String)redisTemplate.opsForValue().get("post_counter_"+cId);
				if(n!=null){
					Integer number = Integer.parseInt(n);
					if(number!=null){
						c.setLikes(c.getLikes()+number);//数据库点赞数+redis点赞数
					}
				}
				resultList.add(c);
			}
		}
		if(resultList.size()>0){
			return resultList;
		}else{
			return null;
		}
	}
	
	
	/**
	 * 图书评论回复
	 * */
	public int insertComment(String userId,int bookId,String blob,Integer fatherId,Integer toId){
		Comment comment = new Comment();
		comment.setBookId(bookId);
		comment.setUserId(userId);
		comment.setCommentMsg(blob);
		comment.setAddTime(new Date());
		comment.setLikes(0);
		comment.setSonComments(0);
		if(fatherId!=null){
			commentMapperWCustom.updateSonCommentsByParmaryKey(fatherId);
			comment.setFatherCommentid(fatherId);
			if(toId!=null){
				commentMapperWCustom.updateSonCommentsByParmaryKey(toId);
				comment.setToId(toId);
			}
		}
		commentMapperWCustom.insertSelectiveReturnKey(comment);
		return comment.getId();
	}
	
	/**
	 * 许愿、以及底下评论回复
	 * */
	public Map<String,Object> insertWishComment(String userId,Wishing wish,String blob,Integer fatherId,Integer toId){
		Map<String,Object> map = new HashMap<String,Object>();
		Comment comment = new Comment();
		comment.setUserId(userId);
		comment.setCommentMsg(blob);
		comment.setAddTime(new Date());
		comment.setLikes(0);
		comment.setSonComments(0);
		if(wish.getId()!=null){
			comment.setWishId(wish.getId());
			if(fatherId!=null){
				commentMapperWCustom.updateSonCommentsByParmaryKey(fatherId);
				comment.setFatherCommentid(fatherId);
				if(toId!=null){
					commentMapperWCustom.updateSonCommentsByParmaryKey(toId);
					comment.setToId(toId);
				}
			}
		}else{
			wish.setUserId(userId);
			wishMapperWCustom.insertReturnPrimaryKey(wish);
			comment.setWishId(wish.getId());
			map.put("wishId", wish.getId());
		}
		commentMapperWCustom.insertSelectiveReturnKey(comment);
		map.put("commentId", comment.getId());
		return map;
	}
	
	/**
	 * 用户删除个人评论
	 * */
	public int deleteMyComment(int commentId,Integer father_id,String userId){
		int result=0;
		if(father_id==null){
			CommentExample example =new CommentExample();
			Criteria c = example.createCriteria();
			c.andUserIdEqualTo(userId);
			c.andIdEqualTo(commentId);
			c.andFatherCommentidIsNull();
			//删除评论
			commentMapperWCustom.deleteByExample(example);
			//删除评论对应的点赞记录
			UserLikeCommentExample uexample = new UserLikeCommentExample();
			UserLikeCommentExample.Criteria uc = uexample.createCriteria();
			uc.andCommentIdEqualTo(commentId);
			masterUserLikeCommentMapper.deleteByExample(uexample);
			//删除redis对应的记录
			setOperations.remove("COMMENT_SET", commentId+"");
			redisTemplate.delete("USER_LIKE_COMMENT_"+commentId);
			redisTemplate.delete("post_counter_"+commentId);
			//删除子评论
			CommentExample sonExample =new CommentExample();
			Criteria sc = sonExample.createCriteria();
			sc.andFatherCommentidEqualTo(commentId);
			List<Integer> intList = clusterCommentMapper.selectKeyByExample(sonExample);
			commentMapperWCustom.deleteByExample(sonExample);
			//删除子评论的redis对应的记录
			for(int i=0;i<intList.size();i++){
				int id = intList.get(i);
				setOperations.remove("COMMENT_SET", id+"");
				redisTemplate.delete("USER_LIKE_COMMENT_"+id);
				redisTemplate.delete("post_counter_"+id);
			}
			result = 1;
		}else{//属于子评论的删除  为假删除
			CommentExample example =new CommentExample();
			Criteria c = example.createCriteria();
			c.andUserIdEqualTo(userId);
			c.andIdEqualTo(commentId);
			c.andFatherCommentidEqualTo(father_id);
			Comment updateComment = new Comment();
			updateComment.setIsShow(0);
			//修改评论状态
			result = commentMapperWCustom.updateByExampleSelective(updateComment, example);
		}
		return result;
	}
	
	
	
	
	
	/**
	 * 管理员删除评论
	 * */
	public int deleteCommentByAdmin(int commentId,Integer father_id){
		int result=0;
		if(father_id==null){
			CommentExample example =new CommentExample();
			Criteria c = example.createCriteria();
			c.andIdEqualTo(commentId);
			c.andFatherCommentidIsNull();
			//删除评论
			commentMapperWCustom.deleteByExample(example);
			//删除评论对应的点赞记录
			UserLikeCommentExample uexample = new UserLikeCommentExample();
			UserLikeCommentExample.Criteria uc = uexample.createCriteria();
			uc.andCommentIdEqualTo(commentId);
			masterUserLikeCommentMapper.deleteByExample(uexample);
			//删除redis对应的记录
			setOperations.remove("COMMENT_SET", commentId+"");
			redisTemplate.delete("USER_LIKE_COMMENT_"+commentId);
			redisTemplate.delete("post_counter_"+commentId);
			//删除子评论
			CommentExample sonExample =new CommentExample();
			Criteria sc = sonExample.createCriteria();
			sc.andFatherCommentidEqualTo(commentId);
			List<Integer> intList = clusterCommentMapper.selectKeyByExample(sonExample);
			commentMapperWCustom.deleteByExample(sonExample);
			//删除子评论的redis对应的记录
			for(int i=0;i<intList.size();i++){
				int id = intList.get(i);
				setOperations.remove("COMMENT_SET", id+"");
				redisTemplate.delete("USER_LIKE_COMMENT_"+id);
				redisTemplate.delete("post_counter_"+id);
			}
			result = 1;
		}else{//属于子评论的删除  为假删除
			CommentExample example =new CommentExample();
			Criteria c = example.createCriteria();
			c.andIdEqualTo(commentId);
			c.andFatherCommentidEqualTo(father_id);
			Comment updateComment = new Comment();
			updateComment.setIsShow(0);
			//修改评论状态
			result = commentMapperWCustom.updateByExampleSelective(updateComment, example);
		}
		return result;
	}
	
	
	
	
	
	/**
	 * 分页条件查询
	 * */
	@SuppressWarnings("rawtypes")
	public Map<String,Object> selectAllComment(int begin,int length,String commentType,String jsonString,List<String> idList,List<Integer> bookidList){
		Map<String,Object> resultMap = new HashMap<String,Object>();
		CommentExample bex = new CommentExample();
		Criteria criteria = bex.createCriteria();
		if(idList!=null){
			if(idList.size()<1){
				return resultMap;//不存在该用户昵称 直接返回空resultMap
			}
			criteria.andUserIdIn(idList);//用户昵称查询
		}
		if(bookidList!=null){
			if(bookidList.size()<1){
				return resultMap;//不存在该图书名称 直接返回空resultMap
			}
			criteria.andBookIdIn(bookidList);//图书名称查询
		}
		if("book".equals(commentType)){
			criteria.andBookIdIsNotNull();
		}else if("wish".equals(commentType)){
			criteria.andWishIdIsNotNull();
		}else if("activity".equals(commentType)){
			criteria.andActivityIdIsNotNull();
		}
		if(!"".equals(jsonString)&&jsonString!=null&&jsonString.length()>0){
			JSONObject json = JSONObject.parseObject(jsonString);
			Map cMap = (Map)json;
			if (cMap != null && !cMap.isEmpty()) {
				Iterator it = cMap.keySet().iterator();
				while(it.hasNext()){
					String name = (String)it.next();
					if(!cMap.get(name).equals(null)){
						if(name.equals("msg")){//评论内容查询
							criteria.andCommentMsgLike("%" + (String)cMap.get(name) + "%");
						}else if(name.equals("isShow")){//是否显示
							criteria.andIsShowEqualTo((int)cMap.get(name));
						}else if(name.equals("likes")){//按点赞数排序
							bex.setOrderByClause("likes  "+cMap.get(name));
						}else if(name.equals("sonComments")){//按子评论数排序
							bex.setOrderByClause("son_comments  "+cMap.get(name));
						}else if(name.equals("addTime")){//按发布时间排序
							bex.setOrderByClause("add_time  "+cMap.get(name));
						}
					}
				}
			}
		}
			
		int allRecord = clusterCommentMapper.countByExample(bex);
		PaginationUtil pagination = new PaginationUtil((begin-1)*length,length,allRecord);
		bex.setPagination(pagination);
		List<Comment> commentList = clusterCommentMapper.selectByExample(bex);
		resultMap.put("allRecord", allRecord);
		resultMap.put("commentList", commentList);
		return resultMap;
	}

	@Override
	public int deleteCommentAndSonComment(int commentId) {
		int i = 0;
		//删除此评论
		commentMapperWCustom.deleteByPrimaryKey(commentId);
		//删除子评论
		CommentExample example = new CommentExample();
		Criteria c = example.createCriteria();
		c.andFatherCommentidEqualTo(commentId);
		commentMapperWCustom.deleteByExample(example);
		i = 1;
		return i;
	}

	@Override
	public int updateCommentByPrimaryKeySelect(Comment comment) {
		return commentMapperWCustom.updateByPrimaryKeySelective(comment);
	}
}
